package com.teatime.client.bus.publish.editors;

import java.util.Calendar;

import com.teatime.client.R;
import com.teatime.client.view.PopupEditor;

import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.content.Context;  

public class DateTimePicker extends PopupEditor {

    private DatePicker mDatePicker;
    private TimePicker mTimePicker;
      
    private int mYear;
    private int mMonth;
    private int mDay;
	private int mHour;
    private int mMinute;
    protected String mBundleSubfix;
    
    public DateTimePicker(Context context) {
        super(context);
        mBundleSubfix = "";
        // TODO Auto-generated constructor stub
        initValues(Calendar.getInstance());
    }

    @Override
	protected int getContentLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.view_datetime_picker;
	}
	
    @Override
    protected void onInitViews() {
    	mDatePicker = (DatePicker)findViewById(R.id.pub_date_picker);
    	mTimePicker = (TimePicker)findViewById(R.id.pub_time_picker);
    }
    
    public void initValues(int year, int month, int day, int hour, int minute) {
    	mYear   = year;
    	mMonth  = month;
    	mDay    = day;
    	mHour   = hour;
    	mMinute = minute;
    }
    
    public void initValues(Calendar c) {
    	initValues(c.get(Calendar.YEAR),
        		c.get(Calendar.MONTH),
        		c.get(Calendar.DAY_OF_MONTH),
        		c.get(Calendar.HOUR_OF_DAY),
        		c.get(Calendar.MINUTE));
    }
    
    @Override
	public void setControlValues() {
		if (mDatePicker != null) {
			mDatePicker.updateDate(mYear, mMonth, mDay);
		}
		
		if (mTimePicker != null) {
			 mTimePicker.setCurrentHour(mHour);
			 mTimePicker.setCurrentMinute(mMinute);
		}
	}
	
	@Override
	public void getControlValues() {
		mYear   = mDatePicker.getYear();
		mMonth  = mDatePicker.getMonth();
		mDay    = mDatePicker.getDayOfMonth();
		mHour   = mTimePicker.getCurrentHour();
		mMinute = mTimePicker.getCurrentMinute();
	}
	
	@Override
	protected String makeFormatted() {
		// TODO Auto-generated method stub
		String text = mYear + "-" + mMonth + "-" + mDay + " " + mHour + ":" + mMinute;
		return text;
	}

	@Override
	public void onSaveData(Bundle bundle) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();
		c.set(mYear, mMonth, mDay, mHour, mMinute, 0);
		bundle.putSerializable(getClass().getName() + mBundleSubfix, c);
	}

	@Override
	public void onRestoreData(Bundle bundle) {
		// TODO Auto-generated method stub
		Calendar c = (Calendar)bundle.getSerializable(getClass().getName() + mBundleSubfix);
		if (c != null) {
			initValues(c);
		}
	}

}
